/* 用于计算一串文本在text中的长度 */

const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')

export function getTextWidth(str, options) {
  const defaulOption = {
    style: 'normal',
    variant: 'normal',
    weight: 'normal',
    size: '14px',
    family: '"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif',
    align: 'start',
    baseline: 'alphabetic'
  }
  options = {
    ...defaulOption,
    ...options
  }

  let size = options.size
  if (typeof size === 'number') size = size + 'px'

  context.font = `${options.style} ${options.variant} ${options.weight} ${size} ${options.family}`
  context.textAlign = options.align
  context.textBaseline = options.baseline

  return context.measureText(str).width
}
